package org.bookie.framework.services.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.util.ContentType;
import org.bookie.framework.services.ChartGenerator;
import org.bookie.framework.services.ChartGenerator.Chart;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;

public class ChartEngineServiceImpl extends CommonEngineService{
	
	private static final ContentType CONTENT_TYPE = new ContentType("image/jpeg");
	public static final String SERVICE_NAME = "chart";
	private int width = 300;
	private int height =200;
	
	/**Injected*/
	private ChartGenerator generator;
	
	public String getName() {
		return SERVICE_NAME;
	}

	public void service(IRequestCycle cycle) throws IOException {
		Object[] parameters = linkFactory.extractListenerParameters(cycle);
		int length = parameters.length;
		if(length<2)return;
		String type = (String)parameters[0];
		Long id = (Long)parameters[1];
		JFreeChart jfree = null;
		if(Chart.USER_TRANSACTIONS.value().equals(type)){
			jfree=generator.createUserTransactionChart(id);
		}else if(Chart.BET_DISTRIBUTION.value().equals(type)){
			jfree=generator.createBetDistributionChart(id);
		}
		if(jfree == null)return;
		if(2<length){
			width = (Integer)parameters[2];
		}
		if(3<length){
			height = (Integer)parameters[3];
		}

		try {
			writeImageResponse(jfree);
		} catch (Exception e) {
			exceptionReporter.reportRequestException("Error creating chart.", e);
		}
	}

    void writeImageResponse(JFreeChart chart) throws IOException{
        BufferedImage image  = chart.createBufferedImage(width, height);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ChartUtilities.writeBufferedImageAsPNG(stream, image);
        OutputStream os = null;
        try {
            response.setDateHeader("Expires", 1);
            byte[] data = stream.toByteArray();
            response.setContentLength(data.length);
            os = response.getOutputStream(CONTENT_TYPE);
            os.write(data);
        }catch(IOException e){
        	throw e;
        }
        finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (Throwable t) {
                // ignore
            }
        }
    }
	
	/**
	 * Setter for ChartGenerator. 
	 * 
	 * @category injector
	 * @param generator generator to inject
	 */
	public void setGenerator(ChartGenerator generator) {
		this.generator = generator;
	}
}
